<template>
  <el-dialog
      @close="handleDialogClose"
      :title="headerTitle"
      :close-on-click-modal="false"
      :visible.sync="detailsVisible"
      :width="dialogWidth"
  >
    <el-row :gutter="20">
      <el-col :span="form.applyType==1?16:9">
        <el-form
            ref="form"
            :model="form"
            label-width="auto"
            :rules="rules"
        >
          <el-form-item label="节假日名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="节假日起止日期" prop="time">
            <!--        <el-input v-model="form.name"></el-input>-->
            <el-date-picker
                :clearable="false"
                style="width: 100%"
                @input="$forceUpdate()"
                value-format="yyyy-MM-dd"
                v-model="form.time"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="应用人员" prop="applyType">
            <el-radio-group v-model="form.applyType" align="left" placeholder="请选择应用人员" @change="updateForm">
              <el-radio :label="0">全部</el-radio>
              <el-radio :label="1">自定义</el-radio>
              <el-radio :label="2">考勤组</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="考勤组列表" v-if="form.applyType==2" prop="selectedAttendanceGroup">
            <el-select
                v-loading="attendanceGroupLoading"
                @change="selectedAttendanceGroupChange"
                v-model="form.selectedAttendanceGroup"
                multiple
                collapse-tags
                placeholder="请选择">
              <el-option
                  v-for="item in attendanceGroupList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <!--      指定人员-->
      <el-col :span="form.applyType>0?6:4" v-if="form.applyType==1">
        <vl-tree v-loading="treeLoading" id="customTree" empty-text="暂无数据" node-key="id"
                 :filter-method="filterNode" ref="orgInfoTree" class="orgTree" show-checkbox
                 :height="300" :props="deprops" :data="noDepartmentPersonnel">
          <div class="custom-tree-node" slot-scope="{ node, data }">
                       <span>
                           <i v-if="data.sex==undefined&&data.id!=-200" class="orgIcon iconfont-KUI icon-modules"></i>
                           <i v-if="data.sex!==undefined" :class="{'female':data.sex==1}"
                              class="el-icon-user-solid userIcon" style="margin-right:5px">
                           </i>
                           <span style="width: 60px;display: inline-block;overflow: hidden;white-space: nowrap;vertical-align: bottom;text-overflow: ellipsis;" class="ellipsis"
                                 :title="node.label">{{ node.label }}</span>
                       </span>
            <span>
                            <!-- <el-tag style="margin-right: 3px" type="info" size="mini"
                                    v-if="data.sex==undefined">{{ getOrgPersionCount(data.children) }}</el-tag> -->
                        </span>

          </div>
        </vl-tree>
      </el-col>
      <!--      考勤组-->
      <!--      <el-col :span="form.applyType>0?13:12" v-if="form.applyType==2">-->
      <!--        考勤组-->
      <!--        <el-select-->
      <!--            v-model="selectedAttendanceGroup"-->
      <!--            multiple-->
      <!--            collapse-tags-->
      <!--            style="margin-left: 20px;"-->
      <!--            placeholder="请选择">-->
      <!--          <el-option-->
      <!--              v-for="item in attendanceGroupList"-->
      <!--              :key="item.id"-->
      <!--              :label="item.name"-->
      <!--              :value="item.id">-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-col>-->
    </el-row>

    <section style="text-align: center">
      <el-button size="small" class="oBtn" @click="handleDialogClose">取消</el-button>
      <el-button size="small" class="oBtn" :loading="saveLoading" type="primary" @click="hanldeConfirm"
      >确定
      </el-button
      >
    </section>
  </el-dialog>
</template>
<script>
import "@/assets/common/css/treeStyle.css";
import {attendancegroupGetlist, holidaysCreate, holidaysUpdate} from "@/api/pcmj/jjr";
import {getdepartmenttree} from "@/api/pcmj/zzxx";
import {filterTreeData} from "@/views/rygl/utils";

export default {
  data() {
    var validateName = (rule, value, callback) => {
      if (value == '') {
        // 请输入节假日名称
        callback(new Error('请输入节假日名称'));
      } else {
        callback();
      }
    };
    var validateTime = (rule, value, callback) => {
      if (value == '') {
        // 请选择日期
        callback(new Error('请选择日期'));
      } else {
        callback();
      }
    };
    var validateApplyType = (rule, value, callback) => {
      if (value === '') {
        // 请选择应用范围
        callback(new Error('请选择应用范围'));
      } else {
        callback();
      }
    };
    var validateSelectedAttendanceGroup = (rule, value, callback) => {
      console.log('考勤组', value);
      if (!value.length) {
        // 请选择考勤组
        callback(new Error('请选择考勤组'));
      } else {
        callback();
      }
    };
    return {
      attendanceGroupList: [],
      deprops: { // 默认配置
        value: 'id', // treeId 为节点id，唯一值
        label: 'name',
        children: 'children',
      },
      orgInfo: [],
      rules: {
        name: [
          {validator: validateName, required: true, trigger: 'blur'},
          {max: 24, message: '长度最大 24 个字符', trigger: 'blur' }
        ],
        time: [
          {validator: validateTime, required: true, trigger: 'blur'}
        ],
        applyType: [
          {validator: validateApplyType, required: true, trigger: 'blur'}
        ],
        selectedAttendanceGroup: [
          {validator: validateSelectedAttendanceGroup, required: true, trigger: 'blur'}
        ],
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      form: {
        name: "",
        time: "",
        applyType: 0,
        startTime: null,
        endTime: null,
        selectedAttendanceGroup: []
      },
      treeLoading: false,
      attendanceGroupLoading: false,
      saveLoading: false,
      defaultExpandedArr: [],
      noDepartmentPersonnel: [],
      dialogWidth: "550px"
    };
  },
  props: {
    detailsVisible: {
      type: Boolean,
      default: false
    },
    handleType: {
      type: String,
      default: "add",
    },
    tableRow: {
      type: Object,
      default: () => {
        return {}
      },
    }
  },
  computed: {
    headerTitle() {
      return this.handleType == 'edit' ? this.i18n.t('Modified holiday') : this.i18n.t('New holiday');
    },
  },
  watch: {
    "form.applyType"(newVal, oldVal) {
      newVal == 1 ? this.dialogWidth = "800px" : this.dialogWidth = "550px"
      console.log('宽度', this.dialogWidth);
      if (newVal == 1) {
        // 指定人员时，获取人员列表
        this.getdepartmenttree()
      } else if (newVal == 2) {
        // 考勤组时，获取考勤组列表
        this.attendancegroupGetlist()
      }
    }
  },
  methods: {
    updateForm() {
      this.$forceUpdate()
    },
    selectedAttendanceGroupChange() {
      console.log(this.form.selectedAttendanceGroup);
      this.$refs.form.clearValidate("selectedAttendanceGroup")
    },
    // 获取选中的人员
    getSelectedPersonnel() {
      var checkedKeys = this.getOrginfoCheckedKeys()
      var result = []
      if (checkedKeys.length) {

        checkedKeys.map(item => {
          if (item.sex !== undefined) {
            var temp = {
              personId: item.id
            }
            result.push(temp)
          }
        })
        // this.selectedPersonList=result

      }
      // else{
      //   // 请在左侧选择要移动的人员!
      //   this.W.$tips("warning", this.i18n.t('Please select the person to move on the left'));
      // }
      console.log('选中的数据', result);
      return result
    },
    // 获取组织树下选中的人员
    getOrginfoCheckedKeys() {
      console.log('选中的原始数据', this.$refs.orgInfoTree.getCheckedNodes());
      return this.$refs.orgInfoTree.getCheckedNodes()
    },
    // 获取组织下的人数
    getOrgPersionCount(item) {
      console.log(item);
      var count = 0
      if (Array.isArray(item)) {
        item.map(res => {
          if (res.sex !== undefined) {
            count++
          }
        })
      }

      return count
    },
    // 获取考勤组列表
    attendancegroupGetlist() {
      this.attendanceGroupLoading=true
      attendancegroupGetlist({
        name: null,
        pageNumber: 1,
        pageSize: 999
      }).then((res) => {
        if (res.code === 200) {
          this.attendanceGroupList = res.data.values
        }
      }).catch().finally(() => {
        setTimeout(()=>{
          this.attendanceGroupLoading=false
        },600)
      })
    },

    /**
     * @description  获取部门人员树
     * @param :
     **/
    getdepartmenttree() {
      this.treeLoading=true
      var allPersonnel=[
        {
          id: -200,
          name: this.i18n.t('All'),
          children: [
            {
              id: -100,
              name: this.i18n.t('default'),
              children: []
            }
          ]
        }
      ]

      this.$nextTick(async () => {
        var params={
          IncludePersonInfo: true,
          // NoAttandanceGroup:true
        }
        // if (this.handleType == 'edit'){
        //   params.attandanceId=this.tableRow.id
        // }
        getdepartmenttree(params).then((res) => {
          if (res.code === 200) {
            // 有组织的人员
            if (res.data.rootDepartments.length) {
              res.data.rootDepartments = filterTreeData(res.data.rootDepartments)
              // 全部分类下，push组织列表
              res.data.rootDepartments.map(item => {
                allPersonnel[0].children.push(item)
              })

            }
            // 无组织的人员
            if (res.data.personnelOfWithOutDepartment.length) {
              // 把无组织的人员，合并到默认分类下
              allPersonnel[0].children[0].children=res.data.personnelOfWithOutDepartment
              console.log(363,allPersonnel[0].children[0].children);
              console.log(364,res.data.personnelOfWithOutDepartment);
            }
            this.noDepartmentPersonnel=allPersonnel
// debugger
            // 默认展开顶级节点
            this.defaultExpandedArr=[this.noDepartmentPersonnel[0].id]
            console.log('this.tableRow',this.tableRow);
            // 编辑时，设置选中的人员
            if (this.handleType == 'edit'&&this.tableRow.holidaysToPeople.length){
              var defaultCheckedKeys=[]
              this.tableRow.holidaysToPeople.map(item=>{
                console.log(item);
                defaultCheckedKeys.push(item.personId)
              })

              console.log('设置选中的数据',defaultCheckedKeys);
              setTimeout(()=>{
                this.$refs.orgInfoTree.setCheckedKeys(defaultCheckedKeys)
              },200)

            }

          }
        }).catch().finally(() => {
          setTimeout(()=>{
            this.treeLoading=false
          },600)
        })

      });
    },
    filterNode() {

    },
    timeChange(val) {
      console.log(val);
    },
    handleDialogClose() {
      // // 关闭dialog时，清空表单数据
      // this.$refs.form.resetFields();
      this.$parent.detailsVisible = false

    },
    // 修改节假日
    holidaysUpdate(params) {
      this.saveLoading = true
      holidaysUpdate(params).then(res => {
        if (res.code == 200) {
          // 修改成功
          this.W.$tips("success", this.i18n.t('Modified successfully!'));
          // 更新父页面表格
          this.$parent.getList()
          this.handleDialogClose()
        }
      }).catch().finally(() => {
        this.saveLoading = false
      })
    },
    // 添加节假日
    holidaysCreate(params) {
      this.saveLoading = true
      console.log('参数', params);
      holidaysCreate(params).then(res => {
        if (res.code == 200) {
          // 添加成功
          this.W.$tips("success", this.i18n.t('Add successfully!'));
          // 更新父页面表格
          this.$parent.getList()
          this.handleDialogClose()
        }
      }).catch().finally(() => {
        this.saveLoading = false
      })
    },
    hanldeConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var params = JSON.parse(JSON.stringify(this.form))
          console.log('this.form', this.form);
          console.log('用户信息：', JSON.parse(localStorage.getItem("userInfo")));
          params.applyType = this.form.applyType * 1
          params.creatorId = JSON.parse(localStorage.getItem("userInfo")).userId
          params.startTime = params.time[0]
          params.endTime = params.time[1]

          delete params.time

          // 指定人员
          if (params.applyType == 1) {
            var selectedPersion = this.getSelectedPersonnel()
            if (!selectedPersion.length) {
              this.W.$tips("warning", "请在右侧选择对应的人员");
              return
            }
            params.holidaysToPeople = selectedPersion
          }
          // 考勤组
          if (params.applyType == 2) {
            if (!this.form.selectedAttendanceGroup.length) {
              this.W.$tips("warning", "请选择应用范围");
              return
            }
            var holidaysToAttendanceGroups = []
            this.form.selectedAttendanceGroup.map(item => {
              var temp = {
                attendanceGroupId: item
              }
              holidaysToAttendanceGroups.push(temp)
            })
            params.holidaysToAttendanceGroups = holidaysToAttendanceGroups
            delete params.selectedAttendanceGroup
          }
          // if (this.handleType=='add'){
          //   params.time0+=":00"
          //   params.time1+=":00"
          // }else{
          //   var time0List=params.time0.split(":")
          //   var time1List=params.time1.split(":")
          //   if (time0List.length==2){
          //     params.time0+=":00"
          //   }
          //   if (time0List.length==3){
          //     // params.time0+=":00"
          //     time0List[2]="00"
          //     params.time0=time0List.join(":")
          //   }
          //
          //   if (time1List.length==2){
          //     params.time1+=":00"
          //   }
          //   if (time1List.length==3){
          //     // params.time0+=":00"
          //     time1List[2]="00"
          //     params.time1=time1List.join(":")
          //   }
          //
          //   params.createBy=params.accountInfo.userName
          //   delete params.loading
          // }

          // delete params.isDefault
          // delete params.id

          console.log('保存的参数', params);
          if (this.handleType == 'edit') {
            this.holidaysUpdate(params)
          } else {
            this.holidaysCreate(params)
          }

          // 更新父页面表格
          // console.log(this.$parent.$parent);
        } else {
          return false;
        }
      })
    },
  },
  mounted() {
    // debugger
    if (this.handleType == 'edit') {
      this.form = JSON.parse(JSON.stringify(this.tableRow))
      this.form.time = [this.form.startTime, this.form.endTime]
      console.log('this.form',this.form);

      // 考勤组
      if (this.form.applyType==2){
        this.$set(this.form,'selectedAttendanceGroup',[])
        if (this.form.holidaysToAttendanceGroups.length){
          this.form.holidaysToAttendanceGroups.map(item=>{
            this.form.selectedAttendanceGroup.push(item.attendanceGroup.id)

            console.log(513,this.form.selectedAttendanceGroup);
          })
          // this.form.selectedAttendanceGroup
        }
      }
      // this.form.timeSpanOfBeLater=this.hmsToMinute(this.form.timeSpanOfBeLater)
      // this.form.timeSpanOfTime0Miss=this.hmsToMinute(this.form.timeSpanOfTime0Miss)
      // this.form.timeSpanOfLeaveEarly=this.hmsToMinute(this.form.timeSpanOfLeaveEarly)
      // this.form.timeSpanOfTime1Miss=this.hmsToMinute(this.form.timeSpanOfTime1Miss)
      // console.log(this.form);
    }
  }
};
</script>
<style scoped lang="scss">
  ::v-deep .el-form .el-form-item {
    width: 500px;
  }
  //
  //::v-deep .el-form .el-form-item__label,
  //::v-deep .el-form .el-form-item__content {
  //  display: inline-block;
  //}
  //
  //::v-deep .el-form .el-form-item__content {
  //  top: 3px;
  //  width: 363px;
  //}
  //
  //.el-radio-group {
  //  width: 100%;
  //}
  //
  //.el-radio {
  //  margin-right: 50px;
  //}
  //
  //.ellipsis {
  //  width: auto;
  //}
  //
  //.oBtn {
  //  padding: 9px 30px;
  //}
</style>
